package com.yuzhihao.writejvm.attributes;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.constant.ConstantUtf8Info;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * The Signature attribute is a fixed-length attribute in the attributes table of a ClassFile, field_info, or method_info structure (§4.1, §4.5, §4.6). A Signature attribute records a signature (§4.7.9.1) for a class, interface, constructor, method, or field whose declaration in the Java programming language uses type variables or parameterized types. See The Java Language Specification, Java SE 8 Edition for details about these types.
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.9">SignatureAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日11:41:52
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class SignatureAttribute extends Attributes {

    private int signature_index_u2 = 2;

    private int signature_index;

    private String constant;

    public SignatureAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.signature_index = Parse.byteToInt(this.signature_index_u2, dis);
        } catch (IOException e) {
            log.error(e);
        }
    }

    @Override
    public String print(String print) {
        StringBuilder builder = new StringBuilder();
        builder.append(print).append("Signature")
                .append(PrintFormat.COLON)
                .append(PrintFormat.EMPTY)
                .append(PrintFormat.HASHTAG)
                .append(this.signature_index)
                .append(PrintFormat.EMPTY)
                .append(PrintFormat.DOUBLE_SLASH)
                .append(PrintFormat.EMPTY)
                .append(this.getConstant())
                .append(System.lineSeparator());
        return builder.toString();
    }

    public String getConstant() {
        if(Objects.nonNull(this.constant)){
            return this.constant;
        }
        ConstantUtf8Info cui = (ConstantUtf8Info)this.getCi().getCp_info().getPools().get(String.valueOf(this.signature_index));
        this.constant = cui.getConstant();
        return constant;
    }
}
